package com.atguigu.gulimall.search.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ ClassName ThreadTest3
 * @ Description TODO
 * @ Author admin
 * @ Date 2021/3/15 17:04
 * @ Version 1.0
 */
public class ThreadTest3 {

    public static ExecutorService executor = Executors.newFixedThreadPool(5);

    public static void main(String[] args) {
        System.out.println("main方法启动...");

        System.out.println("main方法结束...");


    }



    /**
     *
     */
    public static void thenAcceptBothAsync(){
        CompletableFuture<Integer> thread01 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务一启动了....");
            int i = 10 / 2;
            System.out.println("运行结果: " + i);
            return i;
        }, executor);

        CompletableFuture<Integer> thread02 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务二启动了....");
            int i = 10 / 5;
            System.out.println("运行结果: " + i);
            return i;
        }, executor);

        thread01.thenAcceptBothAsync(thread02,(res1,res2)->{
            System.out.println("任务三启动了...."+res1+"==="+res2);
        },executor);
    }

    /**
     * 合并多个线程 ,并有返回值
     */
    public static void thenCombineAsync(){
        CompletableFuture<Integer> thread01 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务一启动了....");
            int i = 10 / 2;
            System.out.println("运行结果: " + i);
            return i;
        }, executor);

        CompletableFuture<Integer> thread02 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务二启动了....");
            int i = 10 / 5;
            System.out.println("运行结果: " + i);
            return i;
        }, executor);

        thread01.thenCombineAsync(thread02,(res1,res2)->{
            System.out.println("任务三启动了...."+res1+"==="+res2);
            return -1;
        },executor);

    }

    /**
     * runAfterBoth必须等两个任务都执行完才执行
     */
    public static void runAfterBothAsync(){
        CompletableFuture<Integer> thread01 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务一启动了....");
            int i = 10 / 2;
            System.out.println("运行结果: " + i);
            return i;
        }, executor);

        CompletableFuture<Integer> thread02 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务二启动了....");
            int i = 10 / 2;
            System.out.println("运行结果: " + i);
            return i;
        }, executor);

        thread01.runAfterBothAsync(thread02,()->{
            System.out.println("任务三启动了.....");
        },executor);
    }


}
